import { useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector, ArticleModelState, Loading, Link } from 'umi';
import InfiniteScroll from 'react-infinite-scroller';
import styles from './index.less';  // 启用css module
// import './index.less';  // 不启用css module
import classNames from 'classnames';


function IndexPage() {
  // 通过useSelector获取model数据
  const {article, loading} = useSelector((state: { article: ArticleModelState, loading:Loading }) => {
    return {
      article: state.article,
      loading: state.loading
    }
  });
  // 通过useDispatch获取dispatch
  const dispatch = useDispatch();

  // 定义分页的状态
  const [page, setPage] = useState(1);
  const [isFetching, setIsFetching] = useState(false);

  const scrollEle = useRef(null);

  useEffect(() => {
    (dispatch({
      type: 'article/getArticleList',
      payload: page
    }) as unknown as Promise<any>).then(res=>{
      setIsFetching(false);
    })
  }, [page]);

  useEffect(()=>{
    function loadMore(){
      if (article.articleLength <= article.articleList.length || isFetching){
        return;
      }
      if (window.innerHeight + window.scrollY > ((scrollEle.current as unknown as HTMLElement).clientHeight+42+64-20)){
        setIsFetching(true);
        setPage(page+1);
      }
    }
    window.addEventListener('scroll', loadMore);
    return ()=>{
      window.removeEventListener('scroll', loadMore);
    }
  }, [article, isFetching])


  return <div className={styles.wrap} ref={scrollEle}>
    <div>
      {article.articleList.map(item => {
        return <Link key={item.id} to={`/article/${item.id}`}>
          <p>{item.title}</p>
          <p>{item.summary}</p>
          <img src={item.cover} alt="" />
          <p>{item.publishAt}</p>
        </Link>
      })}
      {article.articleLength > article.articleList.length && <div>loading...</div>}
    </div>
  </div>
}

export default IndexPage;
